using AutoMapper;
using Domain;
using Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RabbitTraceability.Api.Applications.Command;
using RabbitTraceability.Api.Dtos.Response;
using System.Threading;
using System.Threading.Tasks;

namespace RabbitTraceability.Api.Applications.CommandHandler
{
    /// <summary>
    /// 查询溯源详情的命令处理器
    /// </summary>
    public class GetTraceabilityDetailCommandHandler : IRequestHandler<GetTraceabilityDetailCommand, TraceabilityInfoDto>
    {
        private readonly IRepository<TraceabilityInfo> _repository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetTraceabilityDetailCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository">溯源信息仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetTraceabilityDetailCommandHandler(
            IRepository<TraceabilityInfo> repository,
            IMapper mapper,
            ILogger<GetTraceabilityDetailCommandHandler> logger)
        {
            _repository = repository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理查询溯源详情的命令
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>溯源详情DTO</returns>
        public async Task<TraceabilityInfoDto> Handle(GetTraceabilityDetailCommand request, CancellationToken cancellationToken)
        {
            _logger.LogInformation("查询溯源详情，溯源编号：{TraceabilityId}", request.TraceabilityId);

            // 根据溯源编号查询详情
            var traceabilityInfo = await _repository.GetAll()
                .AsNoTracking()
                .FirstOrDefaultAsync(t => t.TraceabilityId == request.TraceabilityId, cancellationToken);

            if (traceabilityInfo == null)
            {
                _logger.LogWarning("未找到溯源信息，溯源编号：{TraceabilityId}", request.TraceabilityId);
                return null;
            }

            _logger.LogInformation("查询溯源详情成功，溯源编号：{TraceabilityId}", request.TraceabilityId);

            // 将实体映射为DTO
            return _mapper.Map<TraceabilityInfoDto>(traceabilityInfo);
        }
    }
} 